#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import os
import dbus
import dbus.service
import dbus.glib
import gobject
from managers.agent import *
from time import gmtime, strftime
from managers.vhd import freesize
from managers.Ag_Motion import *
from managers.cams import *

class MotionManager(dbus.service.Object):
	def __init__(self, bus_name, agent, object_path="/org/security/agent/motion"):
		dbus.service.Object.__init__(self, bus_name, object_path)
		self.agent = agent
		self.db = agent.getDBManager()
		
	@dbus.service.method("org.security.agent")
	def enable_motion_detect(self,id_camera):
		try:
			self.cameras[id_camera].Activar_Deteccio()
			self.update(id_camera)
			return True
		except:
			print "motion::enable_motion_detect error!"
			return False

	@dbus.service.method("org.security.agent")
	def disable_motion_detect(self,id_camera):
		try:
			self.cameras[id_camera].Desactivar_Deteccio()
			self.update(id_camera)
			return True
		except:
			print "motion::disable_motion_detect error!"
			return False

	@dbus.service.method("org.security.agent")
	def ini_record(self,id_camera):
		try:
			self.cameras[id_camera].Inici_Gravacio_continua()
			self.update(id_camera)
			return True
		except:
			print "motion::ini_record error!"
			return False

	@dbus.service.method("org.security.agent")
	def stop_record(self,id_camera):
		try:
			self.cameras[id_camera].Fi_Gravacio_continua()
			self.update(id_camera)
			return True
		except:
			print "motion::stop_record error!"
			return False

	
	# #################
	# Motion Signals  #
	# #################
	
	@dbus.service.method("org.security.agent")
	def on_movie_start(self,id_camera, path_file):
		try:
			print "Creando video!!!"
			print "IDCAMERA: ", id_camera
			print "PATH_FILE: ", path_file
			self.cameras[id_camera].setRecording(True)
			now = strftime("%s", gmtime())
			self.db.query("INSERT INTO Records values (null,'"+id_camera+"','"+now+"',0,0,'a',0,'"+path_file+"',0)")
			workdir = '/'.join(path_file.split('/')[:-1])
			lliure = freesize(workdir)
			ocupat = (self.agent.MaxSpace - lliure)/100
			while (ocupat > 0.9):
				files = self.db.query("SELECT Path FORM Records WHERE Protected = 0 AND Deleted = 0 ORDER BY Init")
				os.system("rm " + files[0])
				self.db.query("UPDATE Records SET Deleted= 1 "+ "WHERE Path='" + path_file +"'")
				ocupat = (self.agent.MaxSpace -  freesize(workdir))/100
			print "All ok"
			return True
		except:
			print "motion::on_movie_start error!"
			return False

	@dbus.service.method("org.security.agent")
	def on_movie_end(self,id_camera, path_file):
		try:	
			print "Video creat!!!"
			self.cameras[id_camera].setRecording(False)
			now = strftime("%s", gmtime())
			time=self.db.query("SELECT Init FROM Records WHERE Path='" + path_file +"'")
			time = time[0]
			time = time[0]
			duration = int(now)-int(time)
			self.db.query("UPDATE Records SET Duration="+str(duration)+" WHERE Path='" + path_file +"'")
			print "All ok"
			return True
		except:
			print "motion::on_movie_end error!"
			return False
